#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.core import serializers
from django.core.cache import cache
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils import simplejson
from django.views.generic.simple import direct_to_template
from djangotoolbox.http import JSONResponse
from socialbar import barManagerControl, cuponManagerControl, routePageControl, paiementControl
from socialbar import barControl, profileControl, logControl, bootstrapControl,constants
from socialbar.models import Bar, Deal
from google.appengine.api import users
from django.core.urlresolvers import reverse
import logging
import urllib2, urllib
try:
   from urlparse import parse_qs
except ImportError:
   from cgi import parse_qs

MEMCACHE_COORDINATE = 'coordinate'


def writeBarsJson(request):
  logging.debug('Handler : Write Bar Json')
  bars = barControl.getAllBars(request)
  json_response = serializers.serialize("json", bars)
  return HttpResponse(json_response)

def getSimpleBarJson(request):
  barName = request.POST['barName']
  logging.debug('Handler : Get Bar Json' + barName)
  bar = barControl.getBar(barName)
  barControl.saveCurrentBarSession(request, barName)
  barPage = render_to_string('socialbar/barTemplate.html',
      {'barSelected': barControl.getBar(barName)})
  dataToDisplay = set(['dealsUsedCurrentBarCount'])
  json_response = simplejson.dumps({"success" : "OK",
                                    "barPage" : barPage,
                                    'data' : routePageControl.getData(request, dataToDisplay)})
  return HttpResponse(json_response)

def routePage(request, page, barName = None):
  if page is None:
    page = 'NO PAGE'
  logging.debug('Handler : Route page ' + page + ' user: ' + request.user.username)
  bars = barControl.getAllBars(request)
  if barName is not None:
    bar = barControl.getBar(barName)
  else:
    bar = bars[0]
  barControl.saveCurrentBarSession(request, bar.name)
  logControl.logAction(request, 'route', '')
  return direct_to_template(request, 'socialbar/index.html',
      {'bars': bars,
       'barSelected': bar,
       'profile': profileControl.getUserInfo(request),
       'page': page,
       'logoutGoogleUrl' : users.create_logout_url( '/profile') ,
       'priceTable' : paiementControl.getPriceTable() ,
       'data': routePageControl.getData(request, set(['all']))})

def saveCoordinate(request):
  return barControl.saveCoordinate(request)
  
def routeBar(request, barName):
  logging.debug('Handler : route bar' + barName)
  return routePage(request, 'bar', barName)

def loginView(request):
  username = request.POST['username']
  password = request.POST['password']

  user = authenticate(username=username, password=password)
  if user is not None:
    login(request, user)
    logging.debug(profileControl.userToJson(user))
    
    render = render_to_string('socialbar/profile.html',
        {'profile':profileControl.getUserInfo(request)})
    json_response = simplejson.dumps({"success" : "OK",
                                          "page": render})
    return HttpResponse(json_response)
  else:
    json_response = simplejson.dumps({
        'error' : 'no user', 'msg' : 'Mauvais identifiants.' })
    logging.debug(json_response) 
    return HttpResponse(json_response)

def easyGoogleConnect(request):
  logging.debug('Handler : easyGoogleConnect')
  google_user = users.get_current_user()
  if google_user:
      return connectWithGoogleAccount(request)
  else:
      return HttpResponseRedirect( users.create_login_url( '/connectWithGoogleAccount' ) )
    
  
def connectWithGoogleAccount(request):
  logging.debug('Handler : connectWithGoogleAccount')
  google_user = users.get_current_user()
  if google_user:
    user = authenticate(googleUser=google_user, password=constants.customBackendPwd)
    if user is not None:
      login(request, user)
    else:
      logging.debug('Error : no User here')
    
  return routePage(request, 'profile')
   
  

def useDeal(request):
  return HttpResponse(barControl.useDeal(request))

def logoutView(request):
  logging.debug('Handler : Logout')
  logout(request)
  return HttpResponse(status=201)

def createAccount(request):
  return HttpResponse(profileControl.createAccount(request.POST['username'],
      request.POST['mail'], request.POST['password'], request.POST['password2']))
  
def buyDeal(request):
  return HttpResponse(profileControl.buyDeal(request))

def manualBootstrap(request):
  bootstrapControl.boot()
  return HttpResponse(status=201)

def barManager(request):
  return barManagerControl.barManagerConnect(request)
  
def cuponManager(request):
  if barManagerControl.verifyStaff(request) is False:
    return barManagerControl.redirectNotStaff(request)
  return cuponManagerControl.main(request)

def makePurchase(request):
  return direct_to_template(request, 'socialbar/testZooz.html',
      {'test': 1})
  
def emptyPage(request):
  return HttpResponse('Welcome')

def getToken(request):
  if 'cmd' in request.GET and request.GET['cmd'] == 'openTrx':
    return paiementControl.openTrx(request)
  return HttpResponse('Parameter missing')











